<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        class="w-100"
        v-model="queryForm.keyword"
        placeholder="关键字搜索"
      />
      <el-button type="primary" :icon="Search" @click="handleSearch"
        >搜索</el-button
      >
      <el-button type="primary" :icon="Plus" @click="addOrder">
        新增订单
      </el-button>
      <el-button class="green-button" :icon="Plus" @click="refreshTableInfo"
        >刷新</el-button
      >
      <!-- 批量删除按钮 -->
      <!-- <el-button
        type="danger"
        :icon="Delete"
        @click="batchDelete"
        :disabled="selectedRows.length === 0"
      >
        批量删除 ({{ selectedRows.length }})
      </el-button> -->

      <!-- 批量上传按钮 -->
      <!-- <el-button type="success" :icon="Upload" @click="showUploadDialog = true">
        批量上传
      </el-button> -->
    </div>
    <div class="table-con">
      <!-- 批量操作提示 -->
      <div v-if="selectedRows.length > 0" class="batch-tip">
        已选择 {{ selectedRows[0].id }}
        <el-button type="primary" link @click="clearSelection"
          >清除选择</el-button
        >
      </div>

      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        row-key="id"
        highlight-current-row
        @current-change="handleCurrentChange"
        border
      >
        <el-table-column prop="nickName" label="id">
          <template #default="scope">
            {{ scope.row.id }}
          </template>
        </el-table-column>
        <el-table-column prop="nickName" label="用户名" width="120">
          <template #default="scope">
            {{ scope.row.customer.nickName }}
          </template>
        </el-table-column>
        <el-table-column prop="bossName" label="老师名字" width="120">
          <template #default="scope">
            {{ scope.row.customer.bossName }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="电话" width="120">
          <template #default="scope">
            {{ scope.row.customer.phone }}
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="学校" width="120">
          <template #default="scope">
            {{ scope.row.customer.unit }}
          </template>
        </el-table-column>
        <el-table-column prop="adress" label="地址" width="120">
          <template #default="scope">
            {{ scope.row.customer.adress }}
          </template>
        </el-table-column>
        <el-table-column prop="productDescription" label="用户需求">
          <template #default="scope">
            {{ scope.row.productDescription }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="需求状态" width="120">
          <template #default="scope">
            {{ getStatusText(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click="detailProductSelf(scope.row, $event)"
              >需求详情</el-button
            >
            <el-popconfirm
              class="box-item"
              title="确认删除该项?"
              placement="left"
              @confirm="confirmEvent(scope.row)"
              :hide-icon="true"
            >
              <template #reference>
                <el-button link size="small" class="mt-3 mb-3">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <Pagination
      v-model:page="pagination.page"
      v-model:size="pagination.pageSize"
      :total="total"
      @pagination="getTableData"
    />
    <div>
      <context-menu v-model:show="show" :options="optionsComponent">
        <context-menu-item label="操作1" @click="onMenuClick(1)" />
        <context-menu-group label="操作2">
          <context-menu-item label="Item1" @click="onMenuClick(2)" />
          <context-menu-item label="Item2" @click="onMenuClick(3)" />
          <context-menu-group label="Child with v-for 8">
            <context-menu-item
              v-for="index of 6"
              :key="index"
              :label="'Item3-' + index"
              @click="onLoopMenuClick(index)"
            />
          </context-menu-group>
        </context-menu-group>
        <context-menu-item label="刷新" @click="onMenuClick(1)">
          <template #icon>
            <Refresh style="width: 1em; height: 1em; margin-right: 8px" />
          </template>
        </context-menu-item>
        <context-menu-item label="删除" @click="onMenuClick(1)">
          <template #icon>
            <Delete style="width: 1em; height: 1em; margin-right: 8px" />
          </template>
        </context-menu-item>
      </context-menu>
    </div>
    <add-edit
      title="新增订单"
      :visible="showDialog"
      :selectedRows="selectedRows"
      @saveSubmit="saveSubmit"
      @update:visible="showDialog = $event"
    ></add-edit>
    <el-dialog v-model="dialogFormVisible" title="定制商品详情" width="800px">
      <el-row>
        <el-col :span="12"
          ><div class="grid-content ep-bg-purple">用户信息：</div></el-col
        >
        <el-col :span="12"
          ><div class="grid-content ep-bg-purple-light">
            {{ detailData.customer?.nickName }}
          </div></el-col
        >
      </el-row>
      <el-row>
        <el-col :span="12"
          ><div class="grid-content ep-bg-purple">老师姓名：</div></el-col
        >
        <el-col :span="12"
          ><div class="grid-content ep-bg-purple-light">
            {{ detailData.customer?.bossName }}
          </div></el-col
        >
      </el-row>
      <el-row>
        <el-col :span="12"
          ><div class="grid-content ep-bg-purple">电话：</div></el-col
        >
        <el-col :span="12"
          ><div class="grid-content ep-bg-purple-light">
            {{ detailData.customer?.phone }}
          </div></el-col
        >
      </el-row>
      <el-row>
        <el-col :span="12"
          ><div class="grid-content ep-bg-purple">学校：</div></el-col
        >
        <el-col :span="12"
          ><div class="grid-content ep-bg-purple-light">
            {{ detailData.customer?.unit }}
          </div></el-col
        >
      </el-row>
      <el-row>
        <el-col :span="12"
          ><div class="grid-content ep-bg-purple">课题组：</div></el-col
        >
        <el-col :span="12"
          ><div class="grid-content ep-bg-purple-light">
            {{ detailData.customer?.researchGroup }}
          </div></el-col
        >
      </el-row>
      <el-row>
        <el-col :span="12"
          ><div class="grid-content ep-bg-purple">创建时间：</div></el-col
        >
        <el-col :span="12"
          ><div class="grid-content ep-bg-purple-light">
            {{ detailData.customer?.createTime }}
          </div></el-col
        >
      </el-row>
      <el-row>
        <el-col :span="12"
          ><div class="grid-content ep-bg-purple">产品需求：</div></el-col
        >
        <el-col :span="12"
          ><div class="grid-content ep-bg-purple-light">
            {{ detailData.productDescription }}
          </div></el-col
        >
      </el-row>
      <!-- 添加图片展示部分 -->
      <el-row v-if="detailData.productImage && detailData.productImage.trim()">
        <el-col :span="12"
          ><div class="grid-content ep-bg-purple">需求图片：</div></el-col
        >
        <el-col :span="12">
          <div class="grid-content ep-bg-purple-light">
            <div class="image-gallery">
              <el-image
                v-for="(imageUrl, index) in getImageUrls(
                  detailData.productImage
                )"
                :key="index"
                :src="getFullImageUrl(imageUrl)"
                :preview-src-list="getFullImageUrls(detailData.productImage)"
                :initial-index="index"
                fit="cover"
                class="requirement-image"
                :preview-teleported="true"
                loading="lazy"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                    <span>加载失败</span>
                  </div>
                </template>
              </el-image>
            </div>
            <div
              class="image-count"
              v-if="getImageUrls(detailData.productImage).length > 0"
            >
              共 {{ getImageUrls(detailData.productImage).length }} 张图片
            </div>
          </div>
        </el-col>
      </el-row>
      <el-row v-else>
        <el-col :span="12"
          ><div class="grid-content ep-bg-purple">需求图片：</div></el-col
        >
        <el-col :span="12">
          <div class="grid-content ep-bg-purple-light">
            <div class="no-images">
              <el-icon><Picture /></el-icon>
              <span>用户未上传图片</span>
            </div>
          </div>
        </el-col>
      </el-row>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="dialogFormVisible = false">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useTable } from "@/hooks/useTable";
import tableApi from "@/api/table";
import productApi from "@/api/product";
import "@imengyu/vue3-context-menu/lib/vue3-context-menu.css";
import type { MenuOptions } from "@imengyu/vue3-context-menu";
// @ts-ignore
import AddEdit from "@/components/addEditDialog/selfProduct/Index.vue";

// 获取环境变量中的基础URL
const BASE_URL = import.meta.env.VITE_BASE_URL;

const queryForm = reactive({
  keyword: "",
});
const dialogFormVisible = ref(false);
// 批量操作相关
const selectedRows = ref<any[]>([]);
const tableRef = ref();

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    PENDING: "待确认",
    QUOTED: "已报价",
    CONFIRMED: "已确认",
    CANCELLED: "已取消",
  };
  return statusMap[status] || "未知状态";
};

// 处理图片URL的方法
const getImageUrls = (productImage: string): string[] => {
  if (!productImage || !productImage.trim()) {
    return [];
  }
  return productImage
    .split(",")
    .map((url) => url.trim())
    .filter((url) => url);
};

const getFullImageUrl = (imageUrl: string): string => {
  if (!imageUrl) return "";
  // 如果已经是完整URL，直接返回
  if (imageUrl.startsWith("http://") || imageUrl.startsWith("https://")) {
    return imageUrl;
  }
  // 否则拼接BASE_URL
  return `${BASE_URL}${imageUrl}`;
};

const getFullImageUrls = (productImage: string): string[] => {
  return getImageUrls(productImage).map((url) => getFullImageUrl(url));
};

const {
  tableData,
  pagination,
  total,
  loading,
  getTableData,
  handleSearch, //搜索
  refreshTableInfo, //刷新
} = useTable(tableApi.getSelfProductList, queryForm);
let show = ref(false);
const optionsComponent: MenuOptions = reactive({
  zIndex: 3,
  minWidth: 230,
  x: 500,
  y: 200,
});
let showDialog = ref(false);
let customerObj: any = ref({});
const addOrder = async () => {
  if (selectedRows.value.length == 0) {
    ElMessage.error("请选择需要创建订单的定制商品列表");
    return;
  }
  if (selectedRows.value[0].status !== "PENDING") {
    return ElMessage.error("只有待确认订单才能新增订单");
  }
  customerObj = selectedRows.value[0].customer;
  const keyArr: any = Object.keys(customerObj);
  const useArr: any = keyArr.filter((item: any) => {
    return (
      item == "bossName" ||
      item == "nickName" ||
      item == "researchGroup" ||
      item == "unit"
    );
  });
  let flaguser: Boolean = false;
  if (useArr.length > 0) {
    flaguser = useArr.every((element: any) => {
      return customerObj[element] != "";
    });
  } else {
    ElMessage.error("没有用户信息无法创建订单");
    return;
  }
  if (!flaguser) {
    ElMessage.error("用户信息不完整无法创建订单,请前往客户信息列表完善信息");
    return;
  }
  try {
    const flag = await ElMessageBox.confirm(
      `请先创建商品或者从已有商品中下单`,
      "温馨提示",
      {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "el-button--danger",
      }
    );
    if (flag) {
      showDialog.value = true;
    }
  } catch (error) {
    return;
  }
};

// 清除选择
const clearSelection = () => {
  selectedRows.value = [];
  // 清除表格选择状态
  if (tableRef.value) {
    tableRef.value.clearSelection();
  }
};
const handleCurrentChange = (val: any) => {
  selectedRows.value = [val];
};
const onMenuClick = (num: number) => {};
const detailProductSelf = (row: any, e: any) => {
  e.stopPropagation();
  detailData.value = row;
  dialogFormVisible.value = true;
  //   title.value = "编辑";
  //   const { ...rest } = row;
  //   formData = cloneDeep(rest);
};
const detailData = ref<any>({});
const saveSubmit = () => {
  showDialog.value = false;
  refreshTableInfo();
};
const onLoopMenuClick = (index: number) => {};
const confirmEvent = async (row: any) => {
  const res: any = await productApi.deleteSelfProduct(row.id);
  if (res.data.ok) {
    refreshTableInfo();
  }
};
</script>
<style scoped>
.w-100 {
  width: 200px;
  margin-right: 5px;
}

.filter-container {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.upload-container {
  padding: 20px;
}

.template-download {
  margin-top: 15px;
  text-align: center;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.upload-demo {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.upload-demo:hover {
  border-color: #409eff;
}

.el-upload__tip {
  color: #909399;
  font-size: 12px;
  margin-top: 7px;
}

.green-button {
  background-color: #67c23a;
  border-color: #67c23a;
  color: white;
}

.green-button:hover {
  background-color: #85ce61;
  border-color: #85ce61;
}

.batch-tip {
  background-color: #e1f3d8;
  border: 1px solid #b3d8ff;
  border-radius: 4px;
  padding: 8px 12px;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #67c23a;
  font-size: 14px;
}

.image-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.more-images {
  font-size: 12px;
  color: #666;
  margin-left: 5px;
}

.no-image {
  font-size: 12px;
  color: #999;
}

.batch-image-upload {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.batch-image-upload-demo {
  margin-bottom: 15px;
}

.uploaded-urls {
  margin-top: 15px;
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid #ddd;
}

.uploaded-urls h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 14px;
}

.url-tip {
  margin: 8px 0 0 0;
  font-size: 12px;
  color: #666;
  line-height: 1.4;
}

.batch-image-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-start;
}
.ep-bg-purple {
  text-align: right;
  padding: 10px 20px;
  font-weight: 500;
}
.ep-bg-purple-light {
  text-align: left;
  padding: 10px 20px;
}

/* 图片展示相关样式 */
.image-gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 8px;
}

.requirement-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e4e7ed;
  cursor: pointer;
  transition: all 0.3s ease;
}

.requirement-image:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 12px;
}

.image-error .el-icon {
  font-size: 20px;
  margin-bottom: 4px;
}

.image-count {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.no-images {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #909399;
  font-size: 14px;
  padding: 20px 0;
}

.no-images .el-icon {
  font-size: 18px;
}
</style>
